package com.qf.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ViewPagerLoadData.ViewPagerLoad;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cn.trinea.android.common.view.DropDownListView;
import cn.trinea.android.common.view.DropDownListView.OnDropDownListener;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.qf.adapter.FirstPageListAdapter;
import com.qf.adapter.MyViewPagerAdapter;
import com.qf.bean.ViewPagerEntity;
import com.qf.config.AppConfig;
import com.qf.homeproject.NewDatailsActivity;
import com.qf.homeproject.NewHomeActivity;
import com.qf.homeproject.R;

public class ContentFragment_shouye extends Fragment
{

	String[] imgName = { "新房", "二手房", "租房", "资讯", "打折优惠", "最新开盘", "房贷计算", "更多" };
	int[] imgRes = { R.drawable.ic_xinfang, R.drawable.ic_ershou,
			R.drawable.ic_zufang, R.drawable.ic_zixun, R.drawable.ic_youhui,
			R.drawable.ic_kaipan, R.drawable.ic_calculator, R.drawable.ic_more };

	private static Bundle bundle;
	// ListView lv;

	DropDownListView lv;
	GridView gridView;
	ViewPager vPager;

	SimpleAdapter gridAdapter;
	PagerAdapter vPagerAdapter;
	FirstPageListAdapter lViewAdapter;

	private String cityId;
	private String firstWebViewPager;

	// grivView的数据源
	List<Map<String, Object>> gridViewDatas = new ArrayList<Map<String, Object>>();
	// ListView的数据源
	List<Map<String, Object>> listViewDatas = new ArrayList<Map<String, Object>>();

	private String url;
	private View headView;
	private RequestQueue queue;
	List<ViewPagerEntity> viewPagerDatas = new ArrayList<ViewPagerEntity>();
	private RequestQueue queueViewPager;

	public static Fragment newInstance(String id)
	{
		ContentFragment_shouye conFrag_shouye = new ContentFragment_shouye();
		bundle = new Bundle();
		bundle.putString("cityId", id);
		conFrag_shouye.setArguments(bundle);
		return conFrag_shouye;
	}

	Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			if (msg.what == 0)
			{
				List<ViewPagerEntity> datas = (List<ViewPagerEntity>) msg.obj;
				viewPagerDatas.addAll(datas);
				Log.i("ContentFragment_shouye", "Handler中下载下来的数据的集合为:"
						+ viewPagerDatas);
				vPagerAdapter.notifyDataSetChanged();
				viewPagerChangeEvent();
			}
		};
	};

	/**
	 * 加载数据
	 */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{

		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		cityId = getArguments().getString("cityId");
		firstWebViewPager = String.format(AppConfig.FIRST_PAGE_WEBVIEW, cityId);
		initGridViewData();
		loadViewPagerData(handler, firstWebViewPager);
		initListViewData(cityId);

	}

	/*
	 * 对GridView设置监听事件
	 */
	public void initGridEvent()
	{
		gridView.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				Intent intent = new Intent(getActivity(), NewHomeActivity.class);
				startActivity(intent);
			}
		});
	}

	// 运用Volleyurl = String.format(AppConfig.FIRST_PAGE_LISTVIEW, 10, 0, 0,
	// "1");
	private void initListViewData(String cityId)
	{

		url = String.format(AppConfig.FIRST_PAGE_LISTVIEW, 10, 0, 0, cityId);
		queue = Volley.newRequestQueue(getActivity());
		StringRequest request = new StringRequest(url, new Listener<String>()
		{

			@Override
			public void onResponse(String response)
			{
				parseJson(response);

				SimpleDateFormat dateFormat = new SimpleDateFormat(
						"yy-MM-dd HH:mm:ss");
				lv.onDropDownComplete("最后更新时间:" + dateFormat.format(new Date()));
				// lv.setSecondPositionVisible();
				// 数据下载完成之后刷新
				lViewAdapter.notifyDataSetChanged();
			}
		}, new ErrorListener()
		{

			@Override
			public void onErrorResponse(VolleyError error)
			{

			}
		});
		queue.add(request);
		Log.i("info", "======initListViewData====");

	}

	private void parseJson(String json)
	{
		Map<String, Object> map;
		JSONObject obj;
		try
		{
			obj = new JSONObject(json);
			JSONArray array_data = obj.getJSONArray("data");
			for (int i = 0; i < array_data.length(); i++)
			{
				map = new HashMap<String, Object>();
				JSONObject object = array_data.getJSONObject(i);
				map.put("summary", object.getString("summary"));
				map.put("title", object.getString("title"));
				map.put("groupthumbnail", object.getString("groupthumbnail"));
				map.put("id", object.getString("id"));
				listViewDatas.add(map);
			}

			// Log.i("info", "解析之后的数据为:" + listViewDatas);
		}
		catch (JSONException e)
		{
			e.printStackTrace();
		}

	}

	private void loadViewPagerData(Handler handler, String firstWebViewPager)
	{

		queueViewPager = Volley.newRequestQueue(getActivity());
		ViewPagerLoad.loadData(getActivity(), handler, firstWebViewPager,
				queueViewPager);
	}

	private void initGridViewData()
	{
		Map<String, Object> map;
		for (int i = 0; i < imgRes.length; i++)
		{
			map = new HashMap<String, Object>();
			map.put("name", imgName[i]);
			map.put("img", imgRes[i]);
			gridViewDatas.add(map);
		}
		gridAdapter = new SimpleAdapter(getActivity(), gridViewDatas,
				R.layout.item_gridview, new String[] { "name", "img" },
				new int[] { R.id.item_gridview_tv, R.id.item_gview_img });
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		View view = inflater.inflate(R.layout.fragment_shouye, null);
		// lv = (ListView) view.findViewById(R.id.shouye_Id);

		// 第三方的库
		lv = (DropDownListView) view.findViewById(R.id.list_view);

		lv.setDropDownStyle(true);

		headView = inflater.inflate(R.layout.headview, null);
		gridView = (GridView) headView.findViewById(R.id.gview);
		vPager = (ViewPager) headView.findViewById(R.id.vpager_id);

		initGridEvent();
		/**
		 * 第三方库的下拉刷新
		 */
		lv.setOnDropDownListener(new OnDropDownListener()
		{

			@Override
			public void onDropDown()
			{
				initListViewData(cityId);
			}
		});

		lv.setOnBottomStyle(false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub

		vPagerAdapter = new MyViewPagerAdapter(viewPagerDatas, getActivity());
		lViewAdapter = new FirstPageListAdapter(getActivity(), listViewDatas,
				queue);
		Log.i("info", "=================");
		gridView.setAdapter(gridAdapter);

		vPager.setAdapter(vPagerAdapter);

		// 将headView 此headView里边有viewpager和GridView
		lv.addHeaderView(headView); // 必须在setAdaptert()之前执行

		// 设置ListView的适配器

		lv.setAdapter(lViewAdapter);
		toNewDetails();
		addCircle();
		initAutoSmooth();
		super.onActivityCreated(savedInstanceState);
	}

	private TextView msgInfo;

	/**
	 * 设置viewPager滑动的监听事件
	 */
	private void viewPagerChangeEvent()
	{
		msgInfo = (TextView) headView.findViewById(R.id.viewpager_showInfo);
		msgInfo.setText(viewPagerDatas.get(0).getTitle());
		vPager.setOnPageChangeListener(new OnPageChangeListener()
		{

			@Override
			public void onPageSelected(int position)
			{
				// Log.i("info", "position的数值wei:" + position);
				point_Layout.getChildAt(position).setActivated(true);
				msgInfo.setText(viewPagerDatas.get(position).getTitle());
				// point.setFocusable(focusable)
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2)
			{

			}

			@Override
			public void onPageScrollStateChanged(int arg0)
			{
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 设置ViewPager的"自动滑动事件"
	 */
	private int i = 0;

	public void initAutoSmooth()
	{

		// Log.i("info", "定时器方法正在执行");
		final ScheduledExecutorService service = Executors
				.newSingleThreadScheduledExecutor();
		service.scheduleWithFixedDelay(new Runnable()
		{

			@Override
			public void run()
			{
				handler.post(new Runnable()
				{

					// Log.i("info","定时器的执行次数");
					@Override
					public void run()
					{
						vPager.setCurrentItem(i);
						i++;
						if (i > viewPagerDatas.size())
						{
							i = 0;
						}
					}
				});
			}
		}, 1, 3, TimeUnit.SECONDS);
	}

	private LinearLayout point_Layout;
	private android.widget.LinearLayout.LayoutParams params;
	private View point;

	private void addCircle()
	{

		point_Layout = (LinearLayout) headView.findViewById(R.id.scroll_circle);
		// 初始化引导页的小圆点
		for (int i = 0; i < 3; i++)
		{
			View point = new View(getActivity());
			point.setBackgroundResource(R.drawable.scroll_selector_cirle);// 设置引导页默认圆点

			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					10, 10);
			if (i > 0)
			{
				params.leftMargin = 10;// 设置圆点间隔
				point.setActivated(true);
			}

			point.setLayoutParams(params);// 设置圆点的大小

			point_Layout.addView(point);// 将圆点添加给线性布局
		}
	}

	/**
	 * 转到新闻详情页面,需要一个新闻的id
	 */

	String newId;
	String detailsUrl;

	private void toNewDetails()
	{
		lv.setOnItemClickListener(new OnItemClickListener()
		{

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id)
			{
				newId = (String) listViewDatas.get(position - 1).get("id");
				detailsUrl = String.format(AppConfig.NEWS_DETAIL, newId);
				Intent intent = new Intent(getActivity(),
						NewDatailsActivity.class);
				intent.putExtra("newDetailUrl", detailsUrl);
				startActivity(intent);
			}
		});
	}

	@Override
	public void onDestroy()
	{
		// TODO Auto-generated method stub
		super.onDestroy();
		queue.stop();
	}

}
